package com.web.pachong.controller;

import com.common.core.exception.PlatformException;
import com.common.core.utils.JsonUtil;
import com.domain.bean.sys.SysMenu;
import com.domain.bean.dto.SysMenuVO;
import com.pachong.common.BaseController;
import com.pachong.service.SysMenuService;
import com.web.pachong.core.annotation.Log;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author zhuxiaomeng
 * @date 2017/12/13.
 * @email 154040976@qq.com
 * 菜单
 */
@Controller
@RequestMapping(value = "/menu")
public class MenuController extends BaseController {

  @Autowired
  private SysMenuService menuService;

  /**
   * 展示tree
   * @param model
   * @return
   */
  @ApiOperation(value = "/showMenu", httpMethod = "GET", notes = "展示菜单")
  @Log(desc = "展示菜单",type = Log.LOG_TYPE.SELECT)
  @GetMapping(value = "showMenu")
  @RequiresPermissions("menu:show")
  public String showMenu(Model model){
    List<SysMenuVO> menuList = menuService.getMenuVoList();
    model.addAttribute("menus", JsonUtil.toJson(menuList));
    return "/system/menu/menuList";
  }

  @GetMapping(value = "showAddMenu")
  public String addMenu(Model model){
    List<SysMenuVO> menuList = menuService.getMenuVoList();
    model.addAttribute("menus", JsonUtil.toJson(menuList));
    return "/system/menu/add-menu";
  }

  @ApiOperation(value = "/addMenu", httpMethod = "POST", notes = "添加菜单")
  @PostMapping(value = "addMenu")
  @ResponseBody
  public JsonUtil addMenu(SysMenu sysMenu){
    if(StringUtils.isEmpty(sysMenu.getPId())){
      sysMenu.setPId(null);
    }
    if(StringUtils.isEmpty(sysMenu.getUrl())){
      sysMenu.setUrl(null);
    }
    if(StringUtils.isEmpty(sysMenu.getPermission())){
      sysMenu.setPermission(null);
    }
    JsonUtil jsonUtil=new JsonUtil();
    jsonUtil.setFlag(false);
    try{
      if(sysMenu.getMenuType()==2){
        sysMenu.setMenuType((byte)0);
      }
      menuService.save(sysMenu);
      jsonUtil.setMsg("添加成功");
    }catch (PlatformException e){
      e.printStackTrace();
      jsonUtil.setMsg("添加失败");
    }
    return jsonUtil;
  }

}
